﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using MammothMicro.SMTPGuard;
using MammothMicro.SMTPGuard.Common;
using MammothMicro.SMTPGuard.Filter;
using MammothMicro.SmtpGuardFilter.Common;

namespace MammothMicro.SmtpGuardFilter.Filter
{
    /// <summary>
    /// Checks email against RBL
    /// </summary>
    public class RblFilter : IEmailFilter
    {
        private List<string> _list = new List<string>();
        public bool Accept(MailMessage message)
        {
            if (_list.Count == 0)
                return true;


            var address = "";//((IPEndPoint)context.Socket.RemoteEndPoint).Address.ToString();
            var rbl = new RblVerifyIP(address, _list.ToArray());
            if(rbl.BlackList.IsListed)
            {
                var msg = new SerializableMailMessage()
                              {Email = message, Id = new Guid(), FilteredBy = Tools.Filters.RblFilter};
                
                FilterManager.MailStore.Save(msg);
                return false;
            }
            return true; 
        }

        public void Reload()
        {
            var path = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

            path = path.Remove(0, 6);
            var reader = new StreamReader(path + @"\configuration\RblList.txt");
            var text = reader.ReadToEnd().ToLower();
            reader.Close();
            const string delimiter = "\r\n";
            var t = text.Split(delimiter.ToCharArray());
            _list = t.ToList();
        }

        #region IEmailFilter Members

     

        #endregion
    }
}


